<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use App\Models\MoneyTransaction;
use App\Models\MoneyBook;
use App\Models\MoneyCategory;
use App\Models\MoneySubCategory;
use Carbon\Carbon;

class MoneyTransactionController extends Controller
{
    /**
     * 显示记账表单页面
     */
    public function create(Request $request)
    {
        $user = Auth::user();

        // 获取用户的当前默认账本
        $moneyBook = $user->getCurrentDefaultBook();

        if (!$moneyBook) {
            return redirect()->route('user.books')->with('error', '请先创建一个账本');
        }

        // 获取收入分类
        $incomeCategories = MoneyCategory::where('book_id', $moneyBook->id)
            ->where('type', MoneyCategory::TYPE_INCOME)
            ->with('subCategories')
            ->orderBy('sort')
            ->get();

        // 获取支出分类
        $expenseCategories = MoneyCategory::where('book_id', $moneyBook->id)
            ->where('type', MoneyCategory::TYPE_EXPENSE)
            ->with('subCategories')
            ->orderBy('sort')
            ->get();

        // 获取URL参数
        $ai_key = $request->ai_key;
        $ai_data = $ai_key ? cache()->get($ai_key) : null;
        if ($ai_data) {
            $ai_data = $ai_data['data']['res'];
            $type = $ai_data['type'];
            $amount = $ai_data['amount'];
            $category = $ai_data['category_id'];
            $sub_category = $ai_data['sub_category_id'];
            $note = $ai_data['description'];
            $transaction_date = $ai_data['date'];
        } else {
            $type = $request->get('type', 'expense'); // 默认为支出
            $amount = $request->get('amount');
            $note = $request->get('note');
            $category = $request->get('category');
            $sub_category = $request->get('sub_category');
            $transaction_date = $request->get('transaction_date');
        }

        return view('transaction.create', compact(
            'incomeCategories',
            'expenseCategories',
            'type',
            'amount',
            'note',
            'category',
            'moneyBook',
            'transaction_date',
            'sub_category',
            'ai_key',
        ));
    }

    /**
     * 保存记账记录
     */
    public function store(Request $request)
    {
        $user = Auth::user();

        $ai_key = $request->ai_key;
        $ai_edit = $request->ai_edit;

        if ($ai_key && !$ai_edit) {
            $ai_data = cache()->get($ai_key);
            if (! $ai_data) return response()->json([
                'success' => false,
                'message' => '记账超时，请刷新后重试',
            ], 400);

            $category_id = $ai_data['data']['res']['category_id'];
            $sub_category_id = $ai_data['data']['res']['sub_category_id'];
            $type = $ai_data['data']['res']['type'];
            $amount = $ai_data['data']['res']['amount'];
            $transaction_date = $ai_data['data']['res']['date'];
            $description = $ai_data['data']['res']['description'];
            if ($ai_data['type'] == 'image') $image = $ai_data['file'];
            else if ($ai_data['type'] == 'audio') $audio = $ai_data['file'];
            else $text = mb_substr(trim($ai_data['text']), 0, 150);
        } else {
            // 验证输入数据
            $validator = Validator::make($request->all(), [
                'type' => 'required|in:income,expense',
                'amount' => 'required|numeric|min:0.01',
                'category_id' => 'required|integer|exists:money_categories,id',
                'sub_category_id' => 'nullable|integer|exists:money_sub_categories,id',
                'transaction_date' => 'required|date',
                'description' => 'nullable|string|max:255',
            ], [
                'type.required' => '请选择收入或支出类型',
                'type.in' => '类型只能是收入或支出',
                'amount.required' => '请输入金额',
                'amount.numeric' => '金额必须是数字',
                'amount.min' => '金额必须大于0',
                'category_id.required' => '请选择分类',
                'category_id.exists' => '选择的分类不存在',
                'sub_category_id.exists' => '选择的子分类不存在',
                'transaction_date.required' => '请选择日期',
                'transaction_date.date' => '日期格式不正确',
                'description.max' => '备注不能超过255个字符',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }
            $category_id = $request->category_id;
            $sub_category_id = $request->sub_category_id;
            $transaction_date = $request->transaction_date;
            $description = $request->description;
            $amount = $request->amount;
            $type = $request->type;

            // 通过AI编辑的，依旧记录其原始上传内容
            if ($ai_key) {
                $ai_data = cache()->get($ai_key);
                if ($ai_data) {
                    if ($ai_data['type'] == 'image') $image = $ai_data['file'];
                    else $text = mb_substr(trim($ai_data['text']), 0, 150);
                }
            }
        }

        try {
            // 获取用户的当前默认账本
            $moneyBook = $user->getCurrentDefaultBook();

            if (!$moneyBook) {
                return response()->json([
                    'success' => false,
                    'message' => '请先创建一个账本'
                ], 400);
            }

            // 验证分类是否属于该账本
            $category = MoneyCategory::where('id', $category_id)
                ->where('book_id', $moneyBook->id)
                ->first();

            if (!$category) {
                return response()->json([
                    'success' => false,
                    'message' => '选择的分类不属于当前账本'
                ], 400);
            }

            // 如果有子分类，验证子分类是否属于该主分类
            if ($sub_category_id) {
                $subCategory = MoneySubCategory::where('id', $sub_category_id)
                    ->where('category_id', $category_id)
                    ->first();

                if (!$subCategory) {
                    return response()->json([
                        'success' => false,
                        'message' => '选择的子分类不属于该主分类'
                    ], 400);
                }
            }

            // 将字符串类型转换为数字常量
            $typeValue = $type === 'income' ? MoneyCategory::TYPE_INCOME : MoneyCategory::TYPE_EXPENSE;

            // 创建交易记录
            $transaction = MoneyTransaction::create([
                'book_id' => $moneyBook->id,
                'user_id' => $user->id,
                'category_id' => $category_id,
                'sub_category_id' => $sub_category_id,
                'type' => $typeValue,
                'amount' => $amount,
                'transaction_date' => $transaction_date,
                'description' => $description,
                'text' => $text ?? null,
                'image' => $image ?? null,
                'audio' => $audio ?? null,
            ]);

            // 用完删除
            if ($ai_key) cache()->delete($ai_key);

            return response()->json([
                'success' => true,
                'message' => '记账成功',
                'transaction' => [
                    'id' => $transaction->id,
                    'type' => $transaction->type,
                    'amount' => $transaction->amount,
                    'transaction_date' => $transaction->transaction_date,
                    'description' => $transaction->description,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '记账失败，请重试'
            ], 500);
        }
    }

    /**
     * 显示编辑交易记录页面
     */
    public function edit($id)
    {
        try {
            $user = Auth::user();
            $moneyBook = $user->getCurrentDefaultBook();

            if (!$moneyBook) {
                return redirect()->route('user.books')->with('error', '请先创建一个账本');
            }

            $transaction = MoneyTransaction::with(['category', 'subCategory'])
                ->where('id', $id)
                ->where('book_id', $moneyBook->id)
                ->first();

            if (!$transaction) {
                return redirect()->back()->with('error', '交易记录不存在');
            }

            // 获取收入分类
            $incomeCategories = MoneyCategory::where('book_id', $moneyBook->id)
                ->where('type', MoneyCategory::TYPE_INCOME)
                ->with('subCategories')
                ->orderBy('sort')
                ->get();

            // 获取支出分类
            $expenseCategories = MoneyCategory::where('book_id', $moneyBook->id)
                ->where('type', MoneyCategory::TYPE_EXPENSE)
                ->with('subCategories')
                ->orderBy('sort')
                ->get();

            return view('transaction.edit', compact(
                'transaction',
                'incomeCategories',
                'expenseCategories',
                'moneyBook'
            ))->with('transactionId', $id);

        } catch (\Exception $e) {
            return redirect()->back()->with('error', '获取交易记录失败');
        }
    }

    public function storeByAi(Request $request)
    {
        $text = $request->input('text');
        $image = $request->file('image');
        $audio = $request->file('audio');

        $user = Auth::user();
        $moneyBook = $user->getCurrentDefaultBook();

        // 确定使用的功能类型
        $featureType = $image ? 'record_by_image' : ($audio ? 'record_by_audio' : 'record_by_text');

        // 检查用户是否有权限使用该功能
        if (!$user->canUseFeature($featureType)) {
            $limit = non_member_limits[$featureType] ?? 0;

            return response()->json([
                'success' => false,
                'message' => '非会员每天只能使用'.$limit.'次'.non_member_rule_map[$featureType].'，请升级会员享受无限使用特权',
                'redirect_to' => route('membership.benefits')
            ], 403);
        }

        $filePath = '';
        $fileType = 'text';

        // 处理图片
        if ($image) {
            // 验证图片
            $validator = Validator::make($request->all(), [
                'image' => 'required|image|mimes:jpeg,png,jpg|max:5120', // 最大5MB
            ], [
                'image.required' => '请选择图片',
                'image.image' => '文件必须是图片',
                'image.mimes' => '图片必须是 jpeg, png, jpg 格式',
                'image.max' => '图片不能大于5MB',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->errors()->first()
                ], 422);
            }

            try {
                // 保存图片
                $filePath = $image->store('transaction_images/' . date('Ym'), 'public');
                $fileType = 'image';

                // 调用OCR服务识别图片
                $ocrService = new \App\Services\OcrService();
                $text = $ocrService->recognizeImage($filePath);
            } catch (\Exception $e) {
                return response()->json([
                    'success' => false,
                    'message' => '图片识别失败：' . $e->getMessage()
                ], 500);
            }
        }
        // 处理音频
        else if ($audio) {
            // 验证音频
            $validator = Validator::make($request->all(), [
                'audio' => 'required|file|max:10240', // 最大10MB
            ], [
                'audio.required' => '请提供音频文件',
                'audio.file' => '文件格式不正确',
                'audio.max' => '音频文件不能大于10MB',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->errors()->first()
                ], 422);
            }

            try {
                // 保存音频文件
                $filePath = $audio->store('transaction_audio/' . date('Ym'), 'public');
                $fileType = 'audio';

                // 调用音频转写服务
                $audioService = new \App\Services\AudioTranscribeService();
                $transcribeResult = $audioService->transcribeAudio($filePath);

                if (!isset($transcribeResult['success']) || !$transcribeResult['success']) {
                    return response()->json([
                        'success' => false,
                        'message' => '语音识别失败：' . ($transcribeResult['error'] ?? '未能识别出有效内容')
                    ], 500);
                }

                // 从结果中提取文本
                $text = $transcribeResult['result'][0];

                if (empty($text)) {
                    return response()->json([
                        'success' => false,
                        'message' => '语音识别失败，未能识别出有效内容'
                    ], 500);
                }
            } catch (\Exception $e) {
                Log::error('语音处理失败：' . exception_to_string($e));
                return response()->json([
                    'success' => false,
                    'message' => '语音识别失败'
                ], 500);
            }
        }

        $format = MoneyTransaction::formatTextByAi($text, $moneyBook);

        if (! $format || isset($format['res']['error'])) {
            return response()->json([
                'success' => false,
                'message' => $format['res']['error'] ?? '识别失败，请重试'
            ], 500);
        }
        $key = uniqid('transaction_by_ai_');
        cache()->put($key, [
            'text' => $text,
            'file' => $filePath,
            'type' => $fileType,
            'data' => $format
        ], 60*60*24);

        // 如果是非会员，增加使用次数记录
        if (!$user->isMember()) {
            $featureType = $image ? 'record_by_image' : ($audio ? 'record_by_audio' : 'record_by_text');
            $user->incrementUsageCount($featureType);
        }

        return response()->json([
            'success' => true,
            'message' => '识别成功',
            'data' => [
                'key' => $key,
                'data' => $format
            ]
        ]);
    }

    /**
     * 获取单个交易记录详情
     */
    public function show(Request $request, $id)
    {
        try {
            $user = Auth::user();
            $moneyBook = $user->getCurrentDefaultBook();

            if (!$moneyBook) {
                if ($request->wantsJson()) {
                    return response()->json([
                        'success' => false,
                        'message' => '未找到账本数据'
                    ], 400);
                }
                return redirect()->route('user.books')->with('error', '请先创建一个账本');
            }

            $transaction = MoneyTransaction::with(['category', 'subCategory'])
                ->where('id', $id)
                ->where('book_id', $moneyBook->id)
                ->first();

            if (!$transaction) {
                if ($request->wantsJson()) {
                    return response()->json([
                        'success' => false,
                        'message' => '交易记录不存在'
                    ], 404);
                }
                return redirect()->route('details.index')->with('error', '交易记录不存在');
            }

            // 如果是AJAX请求，返回JSON数据
            if ($request->wantsJson()) {
                return response()->json([
                    'success' => true,
                    'transaction' => [
                        'id' => $transaction->id,
                        'type' => $transaction->type == MoneyCategory::TYPE_INCOME ? 'income' : 'expense',
                        'amount' => $transaction->amount,
                        'category_id' => $transaction->category_id,
                        'sub_category_id' => $transaction->sub_category_id,
                        'transaction_date' => $transaction->transaction_date,
                        'description' => $transaction->description,
                        'category' => $transaction->category,
                        'sub_category' => $transaction->subCategory
                    ]
                ]);
            }

            // 否则返回视图，直接传递交易数据
            $transactionData = [
                'id' => $transaction->id,
                'type' => $transaction->type == MoneyCategory::TYPE_INCOME ? 'income' : 'expense',
                'amount' => $transaction->amount,
                'category_id' => $transaction->category_id,
                'sub_category_id' => $transaction->sub_category_id,
                'transaction_date' => $transaction->transaction_date,
                'description' => $transaction->description,
                'category' => $transaction->category,
                'sub_category' => $transaction->subCategory,
                'user' => $transaction->user,
                'created_at' => $transaction->created_at,
                'image' => $transaction->image,
                'text' => $transaction->text,
                'audio' => $transaction->audio,
            ];

            return view('transaction.show', [
                'id' => $id,
                'transaction' => $transactionData
            ]);

        } catch (\Exception $e) {
            if ($request->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => '获取交易记录失败'
                ], 500);
            }
            return redirect()->route('details.index')->with('error', '获取交易记录失败');
        }
    }

    /**
     * 更新交易记录
     */
    public function update(Request $request, $id)
    {
        $user = Auth::user();

        // 验证输入数据
        $validator = Validator::make($request->all(), [
            'type' => 'required|in:income,expense',
            'amount' => 'required|numeric|min:0.01',
            'category_id' => 'required|integer|exists:money_categories,id',
            'sub_category_id' => 'nullable|integer|exists:money_sub_categories,id',
            'transaction_date' => 'required|date',
            'description' => 'nullable|string|max:255',
        ], [
            'type.required' => '请选择收入或支出类型',
            'type.in' => '类型只能是收入或支出',
            'amount.required' => '请输入金额',
            'amount.numeric' => '金额必须是数字',
            'amount.min' => '金额必须大于0',
            'category_id.required' => '请选择分类',
            'category_id.exists' => '选择的分类不存在',
            'sub_category_id.exists' => '选择的子分类不存在',
            'transaction_date.required' => '请选择日期',
            'transaction_date.date' => '日期格式不正确',
            'description.max' => '备注不能超过255个字符',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            // 获取用户的当前默认账本
            $moneyBook = $user->getCurrentDefaultBook();

            if (!$moneyBook) {
                return response()->json([
                    'success' => false,
                    'message' => '请先创建一个账本'
                ], 400);
            }

            // 查找交易记录
            $transaction = MoneyTransaction::where('id', $id)
                ->where('book_id', $moneyBook->id)
                ->first();

            if (!$transaction) {
                return response()->json([
                    'success' => false,
                    'message' => '交易记录不存在'
                ], 404);
            }

            // 验证分类是否属于该账本
            $category = MoneyCategory::where('id', $request->category_id)
                ->where('book_id', $moneyBook->id)
                ->first();

            if (!$category) {
                return response()->json([
                    'success' => false,
                    'message' => '选择的分类不属于当前账本'
                ], 400);
            }

            // 如果有子分类，验证子分类是否属于该主分类
            if ($request->sub_category_id) {
                $subCategory = MoneySubCategory::where('id', $request->sub_category_id)
                    ->where('category_id', $request->category_id)
                    ->first();

                if (!$subCategory) {
                    return response()->json([
                        'success' => false,
                        'message' => '选择的子分类不属于该主分类'
                    ], 400);
                }
            }

            // 将字符串类型转换为数字常量
            $typeValue = $request->type === 'income' ? MoneyCategory::TYPE_INCOME : MoneyCategory::TYPE_EXPENSE;

            // 更新交易记录
            $transaction->update([
                'category_id' => $request->category_id,
                'sub_category_id' => $request->sub_category_id,
                'type' => $typeValue,
                'amount' => $request->amount,
                'transaction_date' => $request->transaction_date,
                'description' => $request->description,
            ]);

            return response()->json([
                'success' => true,
                'message' => '更新成功',
                'transaction' => [
                    'id' => $transaction->id,
                    'type' => $transaction->type,
                    'amount' => $transaction->amount,
                    'transaction_date' => $transaction->transaction_date,
                    'description' => $transaction->description,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新失败，请重试'
            ], 500);
        }
    }

    /**
     * 删除交易记录
     */
    public function destroy($id)
    {
        try {
            $user = Auth::user();
            $moneyBook = $user->getCurrentDefaultBook();

            if (!$moneyBook) {
                return response()->json([
                    'success' => false,
                    'message' => '未找到账本数据'
                ], 400);
            }

            $transaction = MoneyTransaction::where('id', $id)
                ->where('book_id', $moneyBook->id)
                ->first();

            if (!$transaction) {
                return response()->json([
                    'success' => false,
                    'message' => '交易记录不存在'
                ], 404);
            }

            $transaction->delete();

            return response()->json([
                'success' => true,
                'message' => '删除成功'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '删除失败，请重试'
            ], 500);
        }
    }
}
